//
//  Interface.m
//  goldmetal
//
//  Created by mac on 2017/1/19.
//  Copyright © 2017年 宏鹿. All rights reserved.
//

#import "Interface.h"

@interface Interface ()

@property(nonatomic, strong)YYReachability *reachability;

@property(nonatomic, strong)AFHTTPSessionManager *shareManger;

@end


@implementation Interface

+ (Interface *)instance{
    static Interface *_interface = nil;
    static dispatch_once_t onceInterfaceInitialize;
    dispatch_once(&onceInterfaceInitialize, ^{
        _interface = [[Interface alloc]init];
        _interface.shareManger = [AFHTTPSessionManager manager];
        _interface.shareManger.requestSerializer = [AFJSONRequestSerializer serializer];
        _interface.shareManger.responseSerializer = [AFJSONResponseSerializer serializer];
        _interface.shareManger.securityPolicy = [AFSecurityPolicy defaultPolicy];
        _interface.shareManger.securityPolicy.allowInvalidCertificates = YES;
        _interface.reachability =  [YYReachability reachabilityWithHostname:@"www.baidu.com"];
        _interface.reachability.notifyBlock = ^(YYReachability *reachability){
            if (reachability.status == YYReachabilityStatusNone) {
                // [MainRootViewController() loadFail:Tip_String_NO_Network];
                DEF_DEBUG(@"连接失败？？？");
            }else{
                DEF_DEBUG(@"ReachabilityStatusChange status = %@", reachability.status==1?@"蜂窝网络":reachability.status==2?@"wifi":@"未连接");
            }
        };
    });
    return _interface;
}



- (void)reqest:(NSString *)url method:(NSString *)method params:(id)params completion:(ReqCompletion)completion{
    [self reqest:url method:method params:params showTip:NO completion:completion];
}

#pragma mark ---- 基础
- (void)reqest:(NSString *)url method:(NSString *)method params:(id)params showTip:(BOOL)showTip completion:(ReqCompletion)completion{

    NSMutableURLRequest *request = [_shareManger.requestSerializer requestWithMethod:method URLString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:params error:nil];
    request.cachePolicy = NSURLRequestReloadIgnoringCacheData;
    [request setTimeoutInterval:20];
    //setHead
    
//    [request setValue:[Utilities getDeviceInfo] forHTTPHeaderField:@"client-info"];
//    if ([[ConfigData instance] didLogin]) {
//        [request setValue:[[ConfigData instance] currentAccount].token forHTTPHeaderField:@"auth-token"];
//    }
//    if (![request valueForHTTPHeaderField:@"Content-Type"]) {
//        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    }
    InterfaceModel *result = [InterfaceModel new];
    result.method = method;
    result.url = url;
    result.params = params;
    result.header = [request allHTTPHeaderFields];
    result.startDate = [NSDate gk_now64];
    
    
    if (showTip == NO) {
        [SVProgressHUD show];
        [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
        [SVProgressHUD setBackgroundColor:[UIColor clearColor]];
    }
    NSURLSessionDataTask *dataTask = [_shareManger dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        result.endDate = [NSDate gk_now64];
        result.duration = result.endDate-result.startDate;
        
        if (showTip == NO) {
            [SVProgressHUD dismiss];
        }
        
        if (!error) {
            [result yy_modelSetWithJSON:responseObject];
            [result serverException];
        }else {
            result.error = error;
            result.retCode = error.code;
        }
        result.success = (error == nil) ? YES : NO;
        
        
        if (completion) {
            completion(result);
        }
        if (!result.success) {
            DEF_DEBUG(@"error responseObject = %@", responseObject);
        }else{
            DEF_DEBUG(@"url %@ >>>>cost %lldms",result.url ,result.duration);
        }
    }];
    
    [dataTask resume];
    DEF_DEBUG(@"url = %@", url);
}



@end












